package com.supermap.dataservice.project.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.supermap.dataservice.mysql.config.DynamicDataSourceContextHolder;
import com.supermap.dataservice.project.mapper.ExpertConsultationMapper;
import com.supermap.dataservice.util.DateUtil;
import com.supermap.dataservice.util.JSONUtils;
import com.supermap.dataservice.websocket.Message;
import com.supermap.dataservice.websocket.WebSocketService;
import com.supermap.dubbo.api.product.ExpertConsultationService;
import com.supermap.dubbo.api.product.entity.ExpertConsultation;
import com.supermap.dubbo.api.product.entity.ExpertConsultationFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author:zhoujian
 * @Desciption: 专家会商实体
 * @date:2019-07-24 10:35
 * @version:v1.0.0
 */
@Service
@Component
public class ExpertConsultationServiceImpl implements ExpertConsultationService{

    @Autowired(required = false)
    private ExpertConsultationMapper expertConsultationMapper;

    @Autowired
    private WebSocketService webSocketService;

    @Override
    public JSONUtils insertConsultation(JSONObject jsonObject) {
        try
        {
            DynamicDataSourceContextHolder.setDataSourceKey("ds2");
            //将json转换成对象
            ExpertConsultation expertConsultation = JSONObject.toJavaObject(jsonObject , ExpertConsultation.class);
            //入库操作
            int count =expertConsultationMapper.insert(expertConsultation);
            if (count > 0)
            {
                Integer id = expertConsultation.getId();
                if (id != null)
                {
                    //创建聊天记录
                    String chatLocalPath = "/mnt/ChinaApp/MicroService/static/chat/chat_" + id+".txt" ;
                    File file = new File(chatLocalPath);
                    if (!file.exists())
                    {
                        boolean flag = file.createNewFile();
                        if (flag)
                        {
                            expertConsultationMapper.updateChatFileById(id , chatLocalPath);
                        }
                    }
                }
                return  new JSONUtils().setData(expertConsultation).setCountSum(count);
            }else{
                return  new JSONUtils().setCountSum(0).setMsg("插入数据失败").setIsSuccess(false);
            }
        }catch ( Exception ex)
        {
            ex.printStackTrace();
            return  new JSONUtils().setCountSum(0).setMsg("插入数据异常").setIsSuccess(false);
        }
    }

    @Override
    public JSONUtils addJoinUser(int id, String joinUserIds, String joinUserNames) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        int count = expertConsultationMapper.addJoinUser(id,joinUserIds ,joinUserNames);
        if (count > 0)
        {
            return  new JSONUtils().setCountSum(count);
        }else{
            return  new JSONUtils().setCountSum(0).setMsg("添加会商人员失败").setIsSuccess(false);
        }
    }

    @Override
    public JSONUtils delJoinUser(int id, String userId, String joinUserId, String joinUserName) {
        if(userId != null && !"".equals(userId) && joinUserId != null && !"".equals(joinUserId))
        {
            if (userId.equals(joinUserId))
            {
                return new JSONUtils().setMsg("移除用户失败").setIsSuccess(false);
            }
        }
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        int count = expertConsultationMapper.delJoinUser(id,userId,joinUserId ,joinUserName);
        if (count > 0)
        {
            return  new JSONUtils().setCountSum(count);
        }else{
            return  new JSONUtils().setCountSum(0).setMsg("移出会商人员失败").setIsSuccess(false);
        }
    }

    @Override
    public JSONUtils delConsultation(int id, String userId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        int count = expertConsultationMapper.delConsultation(id,userId);
        if (count > 0)
        {
            return  new JSONUtils().setCountSum(count);
        }else{
            return  new JSONUtils().setCountSum(0).setMsg("解散会商失败").setIsSuccess(false);
        }
    }

    @Override
    public JSONUtils selectByPrimaryKey(Integer id) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        ExpertConsultation expertConsultation = expertConsultationMapper.selectByPrimaryKey(id);
        return new JSONUtils().setData(expertConsultation).setCountSum(expertConsultation == null? 0: 1);
    }

    @Override
    public JSONUtils selectConsultationListByJsonUserId(String jsonUserId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        List<ExpertConsultation> list = expertConsultationMapper.selectConsultationListByJsonUserId(jsonUserId);
        return new JSONUtils().setData(list).setCountSum(list == null ? 0: list.size());
    }

    @Override
    public JSONUtils userExistsConsultation(int id, String joinUserName) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        ExpertConsultation expertConsultation = expertConsultationMapper.userExistsConsultation(id , joinUserName);
        return new JSONUtils().setData(expertConsultation).setCountSum(expertConsultation == null ? 0: 1);
    }

    @Override
    public JSONUtils uploadFile(String fileUrl, String fileName , String uploadUserName, Integer consultationId) {
        //2.保存数据库
        //文件上传成功之后插入数据库
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        int count = expertConsultationMapper.insertConsultationFile(consultationId,uploadUserName , fileName,fileUrl);
        if (count > 0)
        {
            Message msg = new Message();
            msg.setUserName("系统");
            msg.setMessage(uploadUserName+ "上传文件\'" + fileName + "\'成功！");
            msg.setCreateTime(DateUtil.DateToString(new Date() , "yyyy-MM-dd HH:mm:ss"));
            //发送群消息
            webSocketService.broadcast( JSONObject.toJSONString(msg), WebSocketService.webSocketSet.get(consultationId));

            return  new JSONUtils().setCountSum(count);
        }else{
            return  new JSONUtils().setCountSum(0).setMsg("上传会商文件失败").setIsSuccess(false);
        }
    }

    @Override
    public JSONUtils selectFileListByConsultation(Integer consultationId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        List<ExpertConsultationFile> expertConsultationFiles = expertConsultationMapper.selectFileListByConsultationId(consultationId);

        return new JSONUtils().setData(expertConsultationFiles).setCountSum(expertConsultationFiles == null ? 0: expertConsultationFiles.size());
    }

    @Override
    public JSONUtils userIsOnline(Integer consultationId, String userName) {
        CopyOnWriteArraySet<WebSocketService> onlineUsers = WebSocketService.webSocketSet.get(consultationId);
        //用户不在会商
        if (onlineUsers != null)
        {
           Iterator<WebSocketService> it = onlineUsers.iterator();
           while (it.hasNext())
           {
               WebSocketService ws = it.next();
               if (ws.getUserName().equals(userName))
               {
                   //用户已经在会商
                   return new JSONUtils().setData(true);
               }else
               {
                   //用户不在会商
                   return  new JSONUtils().setData(false);
               }
           }
            return new JSONUtils().setData(false);
        }else
            return new JSONUtils().setData(false);
    }

    @Override
    public JSONUtils onlineUserList(Integer consultationId) {
        CopyOnWriteArraySet<WebSocketService> onlineUsers = WebSocketService.webSocketSet.get(consultationId);
        List<String> userList = new ArrayList<String>();
        //用户不在会商
        if (onlineUsers != null)
        {
            Iterator<WebSocketService> it = onlineUsers.iterator();
            while (it.hasNext()) {
                WebSocketService ws = it.next();
                userList.add(ws.getUserName());
            }
        }

        return new JSONUtils().setData(userList).setCountSum(userList == null ? 0 : userList.size());
    }

    @Override
    public JSONUtils selectHistoryChat(int id) {
        try{
            DynamicDataSourceContextHolder.setDataSourceKey("ds2");
            String chatFilePath = expertConsultationMapper.historyChat(id);
            StringBuffer historyChat = new StringBuffer();
            //判断文件是否存在,存在则读取，不存在则返回提示
            File file = new File(chatFilePath);
            if (file.exists() && file.isFile())
            {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(chatFilePath), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                   historyChat.append(lineTxt).append(",");
                }
                br.close();
                isr.close();
            }else
            {
                historyChat.append("暂无会商记录！");
            }
            return new JSONUtils().setData(historyChat.toString().substring(0 , historyChat.toString().lastIndexOf(",")));
        }catch (Exception ex)
        {
            System.out.println(ex);
            return new JSONUtils().setIsSuccess(false);
        }
    }

    @Override
    public void saveHistoryChat(int id, String message) {

        String chatLocalPath = "/mnt/ChinaApp/MicroService/static/chat/chat_" + id+".txt";
        BufferedWriter out = null;
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(chatLocalPath , true), "utf-8");
            out = new BufferedWriter(write);
            out.write(message+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}